package com.bjpowernode.contoller;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.bjpowernode.POJO.ProductInfo;
import com.bjpowernode.service.ProductInfoService;
import com.bjpowernode.service.ProductTypeService;
import com.bjpowernode.service.request.PageAndPNameAndTypeIdAndpPriceLikeQuery;
import com.bjpowernode.utils.FileNameUtil;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
/*/prod/split.action*/
@RequestMapping("/prod")
public class ProductInfoAction {

    public static final int PAGE_SIZE = 5;

    private String saveFileName = null;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductTypeService productTypeService;

    // 显示全部商品不分页
    /*@RequestMapping("/split")
    public ModelAndView showAllProduct(){
        ModelAndView modelAndView = new ModelAndView();
        List<ProductInfo> all = productInfoService.getAll();
        modelAndView.addObject("info",all);
        modelAndView.setViewName("product");
        return modelAndView;
    }*/

    // 分页显示商品数据
    @RequestMapping(value = "/splitPage")
    public ModelAndView showSplitProduct(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        // 清空当前的 saveFileName 内容, 为了下次增加或修改的异步 ajax的上传处理。
        PageInfo<ProductInfo> productInfoPageInfo = null;
        saveFileName = null;
        Object prodVo = request.getSession().getAttribute("prodVo");
        if (prodVo != null) {
            productInfoPageInfo = productInfoService.selectByCondition((PageAndPNameAndTypeIdAndpPriceLikeQuery) prodVo, PAGE_SIZE);
//            request.getSession().removeAttribute("prodVo");
            modelAndView.addObject("info", productInfoPageInfo);

            modelAndView.setViewName("product");
            return modelAndView;
        }
        productInfoPageInfo = productInfoService.splitPage(1, PAGE_SIZE);

        modelAndView.addObject("info", productInfoPageInfo);

        modelAndView.setViewName("product");
        return modelAndView;
    }

    // ajax 分页翻页处理
    @ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxSplit(PageAndPNameAndTypeIdAndpPriceLikeQuery likeQuery, HttpSession httpSession) {

        PageInfo<ProductInfo> productInfoPageInfo = productInfoService.selectByCondition(likeQuery, PAGE_SIZE);
        httpSession.setAttribute("info", productInfoPageInfo);
    }

    // 异步ajax 文件上传 添加商品
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage, HttpServletRequest request) {
        // 提取生成文件名UUID + 上传图片的后缀.jpg .png
        System.out.println(pimage);

        saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        // 得到 项目中图片存储的路径
        String path = request.getServletContext().getRealPath("/image_big");
        // 转存 系统硬盘真实路径
        try {
            pimage.transferTo(new File(path + File.separator + saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回客户端 JSOn对象，封装图片的路径，为了在页面实现立即回显
        JSONObject object = new JSONObject();
        object.put("imgurl", saveFileName);


        return object.toString();
    }

    @RequestMapping("/save")
    public String save(ProductInfo info, HttpServletRequest request) {
        info.setpDate(new Date());
        if (saveFileName != null)
            info.setpImage(saveFileName);
        // info 对象中有表单提交上来的 5个数据，有异步 ajax 传来的图片名称，有上架时间的数据
        int num = -1;
        try {
            num = productInfoService.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "增加成功!");

        } else {
            request.setAttribute("msg", "增加失败!");
        }
        return "forward:/prod/splitPage.action?page=1";
    }

    // 根据 商品的 id 查找相应的商品信息
    @RequestMapping("/one")
    public ModelAndView one(Integer pid, PageAndPNameAndTypeIdAndpPriceLikeQuery vo,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        ProductInfo info = productInfoService.getById(pid);
        modelAndView.addObject("prod", info);
        // 将多条件及页码放入Session中，更新处理结束后分页时读取条件和页码进行处理。
        request.getSession().setAttribute("prodVo",vo);
        modelAndView.setViewName("update");

        return modelAndView;
    }

    // 商品修改
    @RequestMapping("/update")
    public ModelAndView update(ProductInfo info) {
        ModelAndView modelAndView = new ModelAndView();
        if (saveFileName != null) {
            info.setpImage(saveFileName);
        }

        int num = -1;
        try {
            num = productInfoService.update(info);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            modelAndView.addObject("msg", "修改成功!");

        } else {
            modelAndView.addObject("msg", "修改失败!");
        }
        modelAndView.setViewName("forward:/prod/splitPage.action");
        return modelAndView;
    }

    // 商品的删除
    @RequestMapping("/delete")
    public ModelAndView delete(Integer pid,PageAndPNameAndTypeIdAndpPriceLikeQuery vo,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        int num = -1;
        try {
            num = productInfoService.deleteById(pid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            modelAndView.addObject("msg", "删除成功!");

        } else {
            modelAndView.addObject("msg", "删除失败!");
        }
        // 将多条件及页码放入Session中，更新处理结束后分页时读取条件和页码进行处理。
        request.getSession().setAttribute("prodVo",vo);
        modelAndView.setViewName("forward:/prod/splitPage.action");
        return modelAndView;
    }

    // 批量删除
    @RequestMapping("/deleteBatch")
    public ModelAndView deleteBatch(String str, PageAndPNameAndTypeIdAndpPriceLikeQuery vo,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        String[] split = str.split(",");
        int[] pids = new int[split.length];
        int count = 0;
        for (String s : split) {
            int i = Integer.parseInt(s);
            pids[count++] = i;
        }
        int num = -1;
        try {
            num = productInfoService.deleteBatch(pids);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            modelAndView.addObject("msg", "删除成功!");

        } else {
            modelAndView.addObject("msg", "删除失败!");
        }
        // 将多条件及页码放入Session中，更新处理结束后分页时读取条件和页码进行处理。
        request.getSession().setAttribute("prodVo",vo);
        modelAndView.setViewName("forward:/prod/splitPage.action");
        return modelAndView;
    }

}
